import re
import requests
from bs4 import BeautifulSoup

cookies ={
    "session": ".eJyrViotTi1SsqpWyiyOT0zJzcxTsjLQUcrJTwexSopKU3WUcvOTMnNSlayUDM3gQEkHrDE-M0XJyhjCzkvMBSmKKTVNMjMDkiamFkq1tQDfeR3n.YLOC4w.Xbnx1QbrvUh8OUPb5jauC_Aau9U"
}

headers = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_16_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.92 Safari/537.36"
}

svg_url = "http://47.103.13.124:8001/static/number.svg"
css_url = "http://47.103.13.124:8001/static/css/phone_svg.css"

url = "http://47.103.13.124:8001/svg"

svg_text = requests.get(svg_url, headers=headers, cookies=cookies).text
css_text = requests.get(css_url, headers=headers, cookies=cookies).text


def get_font_size_from_svg(svg_text):
    pattern = re.compile(r'font-size:(\d+)px')
    res = pattern.findall(svg_text)
    if res:
        return int(res[0])
    else:
        # SVG中font-size默认值为16: http://xahlee.info/js/svg_font_size.html
        return 16


def get_xy_from_css(css_text, classname):
    css_text = css_text.replace('\n', '').replace(' ', '')  # 清理回车、空格，方便正则匹配
    m = '.%s{background:-(\d+)px-(\d+)px;}' % classname
    pattern = re.compile(m)
    res = pattern.findall(css_text)
    if res:
        return res[0]
    else:
        # CSS中font-size默认值为16：https://www.w3schools.com/css/css_font_size.asp
        return 16

def get_y_value_from_svg(svg_text):
    soup = BeautifulSoup(svg_text, 'lxml')
    texts = soup.find_all('text')
    all_y = []
    all_values = []
    for text in texts:
        all_y.append(int(text.attrs.get('y')))
        all_values.append(text.get_text())
    return all_y, all_values


def get_value_from_classname(classname):
    css_x, css_y = get_xy_from_css(css_text, classname)
    css_x, css_y = int(css_x), int(css_y)
    svg_font_size = get_font_size_from_svg(svg_text)
    all_y, values = get_y_value_from_svg(svg_text)
    if classname == 'aka0f1':
        pass
    real_y = [i for i in all_y if css_y <= i][0]  # 获得y轴具体的值
    real_text = values[all_y.index(real_y)]  # 获得某一行text标签中的值
    pos = css_x // svg_font_size  # 获得x轴具体的值
    return real_text[pos]


def crawler():
    r = requests.get(url, headers=headers, cookies=cookies)
    soup = BeautifulSoup(r.text, 'lxml')
    all_d = soup.find('div', class_='media-body').find_all('p')[2].find_all('d')
    phonenumber = []
    for d in all_d:
        class_ = d.attrs.get('class')[0]
        print(class_)
        value = get_value_from_classname(class_)
        phonenumber.append(value)
    print(''.join(phonenumber))


crawler()
